﻿import mysql.connector

class SQL:
    conn = True
    def __init__(self):
        self.connection = False
        try:
            conn = mysql.connector.connect(host='10.108.43.84',user='root',password='root',database='appmarket')
            self.connection = True
        except Exception as e:
            print 'error!',e
            
    def escape(self,string):
        return '%s' % string
    def replace(self,tablename=None,**values):
        if self.connection:
            tablename = self.escape(tablename)
            if values:
                print values
                '''
                key =[]
                value = []
                for k,v in values.items():
                    key.append(k)
                    value.append(v)
                    print k,v
                _keys = ','.join(key)
                _values = '","'.join(value)
                '''
                _keys = ','.join(values.keys())
                _values ='"'+ '","'.join(values.values()) + '"'
                sql_query = "insert into %s (%s) values (%s)" % (tablename,_keys,_values)
                print sql_query
            else:  
                sql_query = "replace into %s default values" % tablename
                try:
                    if values:  
                        self.cursor.execute(sql_query,list(itervalues(values)))  
                    else:         
                        self.cursor.execute(sql_query)
                        self.conn.commit()
                        return True
                except Exception,e:
                    print "An Error Occured: ",e
                    return False